Imports cmplib01
Imports FMPLib01
Imports System.Drawing
Imports Microsoft.Win32
Imports System.Drawing.Drawing2D

Imports CampaignerCombatEngine

Imports System.Runtime.Serialization


Public Class frmCampaigner

    Const WM_NCHITTEST As Integer = &H84
    Const HTCLIENT As Integer = &H1
    Const HTCAPTION As Integer = &H2
    Const c_Module As String = "Campaigner"
    Const c_COMBATPHASES As Integer = 50
    Private last As Point '// this is for form moving
    Private _param As String = "xxxxxx-xxxx-xxxx-xxxxxx"

    Private Enum EnablementLevel
        NoneEnable = 0
        GameLoaded = 1
        PlayerLoggedIn = 2
        PlayerLoggedOut = 3
        UnitSelected = 4
        ModeratorLoggedIn = 5
        PlayerLoggedInCombatTurn = 6  ' you can't set waypoints but you can see where combats will occur.
        CombatResolutionPhase = 7
    End Enum

    Private Enum DisplayIconSize
        LargeIcon = 0
        MediumIcon = 1
        SmallIcon = 2
    End Enum

    Private Enum TurnMode
        NormalTurn = 0
        CombatTurn = 1
    End Enum

    Private _GameTitle As String = "Campaigner: No Game Loaded"
    Private CurrentGame As New CampaignerGameData()
    Private GameLoaded As Boolean
    Private bchitSelected As Boolean
    Private mTurnMode As TurnMode = TurnMode.NormalTurn
    Private ptrSelectedBattle As Battle
    Private stopReplay As Boolean = True
    Private headerFont As New Font("Cambria", 16)

    'Private _DisplayIconMode As DisplayIconSize = DisplayIconSize.LargeIcon
    Private _DeployUnit As Boolean
    Private _ToolBarEnablementLevel As EnablementLevel = EnablementLevel.NoneEnable '// only open and exit are enabled
    Private WithEvents newTurnGrinder As New CampaignerCombatEngine.CampaignerCombatEngineB 'CampaignerCombatEngine.ConquestCombatEngine 'CampaignerCombatEngine.CampaignerCombatEngineB

    Private comCombats As New camp128c.ctlCombats()
    Private WithEvents resCombatResolution As New camp128c.ctlCombatResolution

    Private _authenticated As Boolean

    Public Property GameTitle() As String
        Get
            Return _GameTitle
        End Get
        Set(ByVal value As String)
            _GameTitle = value
            Try
                Me.Invalidate()
            Catch ex As Exception

            End Try
        End Set
    End Property


    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
        Select Case m.Msg
            Case WM_NCHITTEST
                MyBase.WndProc(m)
                If (m.Result.ToInt32 = HTCLIENT) Then
                    m.Result = IntPtr.op_Explicit(HTCAPTION)
                End If
                Exit Sub
        End Select
        MyBase.WndProc(m)
    End Sub


    Private Sub Client_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
        e.Graphics.FillRectangle(New LinearGradientBrush(New Point(4, 4), New Point(Me.Width + 10, Me.Height), Color.Navy, Color.Indigo), New RectangleF(4, 4, Me.Width + 10, 36))
        e.Graphics.DrawImage(My.Resources.lendcap, 4, 3)
        e.Graphics.DrawImage(My.Resources.campaigner, 12, 14)
        e.Graphics.DrawString(GameTitle, headerFont, Brushes.AliceBlue, 36, 8)
    End Sub


#Region "Toolbar Stuff"

    Private Sub tlbToolbar_ButtonClicked(ByVal sender As campTSa.cButton) Handles tlbToolbar.ButtonClicked
        Try

            Select Case sender.Text
                Case "New"
                    '// we open a CGD file and log the moderator in, then pop up the moderator form. CHA!
                    If NewGame() = True Then ToolBarEnablementLevel = EnablementLevel.GameLoaded
                Case "Exit" : Me.Close() 'task: confirm closing
                Case "Open"
                    If OpenGame() = True Then ToolBarEnablementLevel = EnablementLevel.GameLoaded
                Case "Save"
                    SaveGame()
                Case "Log Off"
                    ToolBarEnablementLevel = EnablementLevel.PlayerLoggedOut
                Case "Log On"
                    DoLogon()
                Case "Moderator"
                    Moderator()
                Case "Next Player"
                    NextPlayer()
                Case "Manager"
                    Dim fman As New frmManager(CurrentGame)
                    fman.ShowDialog()
                Case "Deploy"
                    DeployUnit = Not DeployUnit
                    If DeployUnit Then
                        updatePointsAvailableText()
                        lblPointsAvailable.Visible = True
                    Else
                        lblPointsAvailable.Visible = False
                    End If
                Case "Resources"
                    If ToolBarEnablementLevel = EnablementLevel.PlayerLoggedIn Then
                        'Dim fRes As New frmResourceManager
                        Dim fres As New frmResourceListing
                        fRes.ShowDialog(CurrentGame)
                        chiSelected.ShowSelectedChitProperties(chiSelected.SelectedChit, CurrentGame)
                    End If
                    'Case "Victory"
                    '    If CurrentGame.selectedFaction Is Nothing Then Exit Sub

                    '    Dim fVictory As New frmVictoryConditions
                    '    fVictory.Victory = CurrentGame.selectedFaction.FactionVictoryConditions

                    '    fVictory.ShowDialog()

                Case "Campaign"
                    If CurrentGame.selectedFaction Is Nothing Then Exit Sub
                    Dim fVictory As New frmVictoryConditions
                    Dim eFaction As Faction
                    Dim fFaction As Faction = CurrentGame.selectedFaction

                    For Each fkey As String In CurrentGame.Faction_g.HT.Keys
                        If CurrentGame.Faction_g.Item(fkey).Equals(CurrentGame.selectedFaction) Then
                            fFaction = CurrentGame.Faction_g.Item(fkey)
                        Else
                            eFaction = CurrentGame.Faction_g.Item(fkey)
                        End If
                    Next

                    fVictory.GameData = CurrentGame
                    fVictory.Victory = fFaction.FactionVictoryConditions
                    fVictory.EnemyVictory = eFaction.FactionVictoryConditions
                    fVictory.ShowDialog()

                Case "Log"
                    Dim flog As New camp128c.frmLog()
                    flog.showdialog(CurrentGame)

            End Select

            tlbToolbar.DoPaint()

        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try

    End Sub

    Private Sub updatePointsAvailableText()
        Try
            lblPointsAvailable.Text = "Faction Points Available: " & CurrentGame.selectedFaction.FactionFreePoints
        Catch ex As Exception
            lblPointsAvailable.Text = "Faction Points Available: Unknown"
        End Try
    End Sub

    Private Property ToolBarEnablementLevel() As EnablementLevel
        Get
            Return _ToolBarEnablementLevel
        End Get
        Set(ByVal Value As EnablementLevel)
            _ToolBarEnablementLevel = Value

            '// default disable all
            With tlbToolbar
                .saveButton.Enabled = False
                .logonButton.Enabled = False
                .moderatorButton.Enabled = False
                .nextPlayerButton.Enabled = False
                .deployButton.Enabled = False
                .deployButton.checked = False
                _DeployUnit = False
                .managerButton.Enabled = False
                .resourcesButton.Enabled = False
                .victoryButton.Enabled = False
                .LogButton.Enabled = False
            End With

            Select Case _ToolBarEnablementLevel
                Case EnablementLevel.NoneEnable
                    '// only open and exit are enabled, and they always are.
                Case EnablementLevel.GameLoaded
                    With tlbToolbar
                        .logonButton.Enabled = True
                        .saveButton.Enabled = True
                    End With
                    GameTitle = "Campaigner: " & " [" & CurrentGame.GameName & "]"

                Case EnablementLevel.PlayerLoggedIn
                    With tlbToolbar
                        .nextPlayerButton.Enabled = True
                        fmpMap.RepositionButtonVisible = False

                        If mTurnMode = TurnMode.NormalTurn Then
                            .deployButton.Enabled = True
                            .deployButton.checked = False
                            .resourcesButton.Enabled = True

                            If CurrentGame.AllowPlayerManageChits Then
                                .managerButton.Enabled = True
                                fmpMap.RepositionButtonVisible = True
                            End If
                        End If
                        .victoryButton.Enabled = True
                        .logonButton.Enabled = True
                        .saveButton.Enabled = True
                        .LogButton.Enabled = True

                        tlbToolbar.logonButton.Text = "Log Off"

                    End With
                    LogPlayerIn()
                    CurrentGame.selectedFaction = CurrentGame.Faction_g.Item(CurrentGame.selectedPlayer.FactionKey)
                    GameTitle = "Campaigner: " & " [" & CurrentGame.GameName & "-" & CurrentGame.selectedPlayer.PlayerName & "] (" & CurrentGame.ElapsedTime.ToString & ")"


                Case EnablementLevel.PlayerLoggedOut
                    lblPointsAvailable.Visible = False
                    tlbToolbar.logonButton.Enabled = True
                    tlbToolbar.saveButton.Enabled = True
                    tlbToolbar.logonButton.Text = "Log On"
                    tlbToolbar.nextPlayerButton.Enabled = False
                    LogPlayerOut()
                    GameTitle = "Campaigner: " & " [" & CurrentGame.GameName & "]"

                Case EnablementLevel.UnitSelected

                Case EnablementLevel.ModeratorLoggedIn
                    tlbToolbar.moderatorButton.Enabled = True
                    tlbToolbar.nextPlayerButton.Enabled = False
                    tlbToolbar.logonButton.Enabled = True
                    tlbToolbar.managerButton.Enabled = True
                    LogModeratorIn()
                    GameTitle = "Campaigner: " & " [" & CurrentGame.GameName & "-Moderator] (" & CurrentGame.Turn & ")"

            End Select
        End Set
    End Property

#End Region
    

    '// File operations
    Private Function NewGame() As Boolean

        Try
            If ContinueThroughGameLoaded() = False Then Return False

            '// the first operation in a series for creating a new game.
            Dim res As Boolean
            res = OpenGame("Campaigner Game Data | *.cgd", True)

            If res = True Then
                If CurrentGame.LogEvents Is Nothing Then CurrentGame.LogEvents = New Collection

                CurrentGame.LogEvents.Add(New CampaignerLogEvent("New Campaign Started", "Campaigner", "No Time", "<none>", EventAuthorityLevel.PublicEvent))

                CurrentGame.gameEndDetails = New EndGame

                '// before any players are created, we run the preparecampaign sub
                newTurnGrinder.PrepareCampaign(CurrentGame)

                '// the second operation is to show the moderator dialog
                Moderator()
            Else
                Return False
            End If

            GameLoaded = True

            Return True

        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try
    End Function


    Private Function OpenGame(Optional ByVal filter As String = "Campaigner Game | *.c7campaign", Optional ByVal ignore As Boolean = False) As Boolean
        ' we must check to see if there are unresolved combats and such so we get into the right turnmode
        If Not ignore Then
            If ContinueThroughGameLoaded() = False Then Return False
        End If

        Dim frmOpenGame As OpenFileDialog
        Dim allPlayersCombatComplete As Boolean

        frmOpenGame = New OpenFileDialog
        frmOpenGame.Filter = filter
        frmOpenGame.ShowDialog()

        ' clear the existing game and put in the new one
        CurrentGame = New CampaignerGameData
        fmpMap.FlexMap = New FlexMapData

        If frmOpenGame.FileName = "" Then Return False

        Try
            CurrentGame = CurrentGame.Open(frmOpenGame.FileName)

            '// do a check to make sure we can open the game
            'If _authenticated = False Then
            '    '// get the DEMO game value
            '    Dim obj As Object = CurrentGame.SystemValue("datamap")
            '    If TypeOf obj Is String Then
            '        If obj = "NoItem" Then
            '            CurrentGame.SetUpDataMapping()
            '            obj = CurrentGame.SystemValue("datamap")
            '        End If
            '    End If

            '    Dim dataMap() As Byte = obj
            '    'we're not authenticated and this is a demo game
            '    If dataMap(221) = 0 Then Throw New FieldAccessException
            'Else
            '    '// to prevent authkey sharing
            '    If checkParams() = False Then
            '        MessageBox.Show("Duplicate authentication key has been detected. Please purchase a copy of your own.", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            '        Return False
            '    End If
            'End If


            ' we need to recalculate averageunitpv and averageobjectivemaxpv, just to make sure its right on startup
            CurrentGame.AverageUnitMaxPV = CalculateAverageMaxPV(GroundChitClass_cgd.Unit)
            CurrentGame.AverageObjectiveMaxPV = CalculateAverageMaxPV(GroundChitClass_cgd.Objective)
            CurrentGame.MaxPointValueDeployed = CalculateMaxDeployedPV(GroundChitClass_cgd.Unit)

            ' set the map without objectives, or units
            ' find the map its always under the campaigns\maps directory really.
            Dim totalPath As String = System.AppDomain.CurrentDomain.BaseDirectory & "\campaigns\maps\"
            fmpMap.ShowMapOnly = True
            fmpMap.OpenFlexMapFromGame(CurrentGame)
            GameLoaded = True
            GameTitle = "Campaigner [" & CurrentGame.GameName & "] (" & CurrentGame.Turn & ")"

            tlbToolbar.Invalidate()


            ' TASK: Handle this better right here.
            If CheckForUnresolvedCombats(allPlayersCombatComplete) = True Then
                mTurnMode = TurnMode.CombatTurn
                ToolBarEnablementLevel = EnablementLevel.CombatResolutionPhase
                If allPlayersCombatComplete Then
                    ShowCombatResolution()
                Else
                    '// don't do anything special?
                End If

            End If

            '// the uhm...selected chit statistics
            chiSelected.GameData = CurrentGame
            chiSelected.MapData = fmpMap.FlexMap
            chiSelected.PopulateStatisticBenchmarks()

            fmpMap.RedrawAndRender()

            '// make sure we have an event log
            If CurrentGame.LogEvents Is Nothing Then CurrentGame.LogEvents = New Collection

            Return True
        Catch serEx As SerializationException
            MessageBox.Show(serEx.Message, "Can't load file", MessageBoxButtons.OK)
            Return False
        Catch demoEx As FieldAccessException
            'MessageBox.Show("You cannot open a non-demo game with the demo version of Campaigner.", "Campaigner Demo", MessageBoxButtons.OK)
            Dim c As New Cryptkeeper
            Dim s1 As String = "Zpv dboopu pqfo b opo-efnp hbnf xjui uif efnp wfstjpo pg Dbnqbjhofs."
            Dim s2 As String = "Dbnqbjhofs Efnp"

            MessageBox.Show(c.DString(s1), c.DString(s2), MessageBoxButtons.OK)

            Return False
        Catch ex As Exception
            HandleException(c_Module, ex)
            Return False
        End Try

    End Function

    Private Function ContinueThroughGameLoaded() As Boolean
        If GameLoaded = True Then
            Dim messres As DialogResult = MessageBox.Show("There is already a game loaded, do you want to create a new game and lose progress on the current game?", "Abandon Current Game?", MessageBoxButtons.YesNo)
            If messres = Windows.Forms.DialogResult.No Then
                Return False
            Else
                Return True
            End If
        Else
            '// if there is no game in progress, return true
            Return True
        End If
    End Function

    Private Sub SaveGame()
        Dim frmSaveGame As SaveFileDialog
        frmSaveGame = New SaveFileDialog
        frmSaveGame.Filter = "Campaigner Game | *.c7campaign"

        frmSaveGame.ShowDialog()

        Try
            If frmSaveGame.FileName = "" Then Exit Sub

            CurrentGame.Save(frmSaveGame.FileName)
        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try

    End Sub

    Private Sub DoLogon()
        Try
            If CurrentGame.Players.Count = 0 Then
                MessageBox.Show("There are no players in this game. The moderator must create players first.", "No Players", MessageBoxButtons.OK)
                Exit Sub
            End If

            ' if there are unresolved combats, only show players that are in combat, and the logon form is smart enough 
            ' to deal with it.

            '// make sure no one is still logged in
            LogPlayerOut()

            Dim frmLogon As New frmCampaignerPasswordDialog(CurrentGame)

            frmLogon.ShowDialog()
            If frmLogon.ActionCancelled = False Then
                ' user has logged in
                If CurrentGame.selectedPlayer.PlayerName = "<Moderator>" Then
                    ToolBarEnablementLevel = EnablementLevel.ModeratorLoggedIn

                    tlbToolbar.logonButton.Text = "Log Off"
                    CheckForEndGame()
                Else
                    ToolBarEnablementLevel = EnablementLevel.PlayerLoggedIn

                    tlbToolbar.logonButton.Text = "Log Off"
                    CheckForEndGame()
                End If

            End If

        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try
    End Sub

    Private Sub LogPlayerIn()
        ' we make sure the current player is logged out
        Try
            fmpMap.ShowMapOnly = False ' automatically redraws map
            ' check for combat turn
            If mTurnMode = TurnMode.CombatTurn Then

                '// we need to see if all players who are in the combat turn are finished, if not, then

                comCombats.Visible = True
                chiSelected.Visible = False
                comCombats.MapBMP = fmpMap.MapBMP
                comCombats.FMVMap = fmpMap.FlexMap
                comCombats.Game = CurrentGame
                resCombatResolution.Visible = False

            Else
                comCombats.Visible = False
                chiSelected.Visible = True
                resCombatResolution.Visible = False
            End If


            fmpMap.RedrawAndRender()
        Catch ex As Exception
            HandleException("frmCampaignRunner.LogPlayerIn", ex)
        End Try

    End Sub

    Private Function AllCombatPlayersComplete() As Boolean

        For Each p As Player In CurrentGame.Players
            If p.IsInCombat Then
                '// check the noplay flag
                If p.NoPlay = False Then
                    If p.TurnComplete = False Then Return False
                End If

            End If
        Next

        '// if we get through all the players and arrive here, they're all done.
        Return True

    End Function

    Private Sub LogPlayerOut()
        Try
            CurrentGame.selectedPlayer = Nothing
            fmpMap.SelectedChit = Nothing

            chiSelected.ClearSelectedList()
            comCombats.ClearData()

            fmpMap.ShowMapOnly = True
            fmpMap.Deployment = False '// just make it clear we're not in deployment mode no more. :P

            tlbToolbar.logonButton.Text = "Log On"
            '// just in case the moderator was logged in, we want to get rid of the reposition option
            fmpMap.ModeratorLoggedOut()

            '// make sure replay isn't going
            fmpMap.HaltReplay()

        Catch ex As Exception
            HandleException("frmCampaignRunner.LogPlayerOut", ex)
        End Try
    End Sub

    Private Sub LogModeratorIn()
        Try
            'casAssets.Refresh()
            fmpMap.ShowMapOnly = False
            'eveEventList.Enabled = True
            'mssCenter.Enabled = True
            'eveEventList.Visible = True
            'mssCenter.Enabled = False
            'eveEventList.ListEvents(CurrentGame)
            'mssCenter.ShowMessages(CurrentGame)
            fmpMap.ModeratorLoggedIn()
            fmpMap.RedrawAndRender()

        Catch ex As Exception
            HandleException("frmCampaignRunner.LogModeratorIn", ex)
        End Try
    End Sub

    Private Sub NextPlayer()
        Try

            SetParams()

            CurrentGame.selectedPlayer.TurnComplete = True
            CurrentGame.selectedPlayer = Nothing

            ' check each player to determine if everyone is done
            Dim play As Player
            Dim key As String
            Dim numComplete As Int16
            Dim totalPlayers As Int32
            Dim turnComplete As Boolean

            totalPlayers = CurrentGame.Players.Count - 1    ' minus one for the moderator

            turnComplete = AllPlayersCompleted()

            LogPlayerOut()

            ToolBarEnablementLevel = EnablementLevel.PlayerLoggedOut

            ' the turn is done if all players are done.
            If turnComplete Then
                ' check if this is a combat turn or was a combat turn and needs to be processed.
                If mTurnMode = TurnMode.NormalTurn Then
                    GenerateTurn()
                    ' reset player complete
                    ResetPlayerComplete()
                    ' check to see if this should be turned into a combat turn.
                    If CurrentGame.Battles_g.HT.Count > 0 Then
                        mTurnMode = TurnMode.CombatTurn
                        ' if it is a combat turn, reset player status for players engaged in combat. Returns the number of players
                        ' that are NOT in combat
                        '// a combat turn! Whoohoo!
                        resCombatResolution.Visible = False
                        chiSelected.Visible = False
                        comCombats.Visible = True
                        numComplete = ResetForCombatPlayers()
                    Else
                        '// turn it off here boss man
                        chiSelected.Visible = True
                        comCombats.Visible = False
                    End If
                Else
                    ' yeah. its a combat turn, lets do what we need to (the combat turn is over)
                    ' show the orders of battle
                    Dim fBattleList As New frmBattlesListing
                    fBattleList.ShowDialog(CurrentGame, fmpMap.FlexMap, fmpMap.MapBMP)
                    '// here is where we'll show the combat resolutions screen instead of a popup. This control will have a button
                    '// to apply the combatresults 
                    ShowCombatResolution()

                End If

                '// tell the toolbar to reset color of buttons
                tlbToolbar.ResetToNormalColors()
                tlbToolbar.DoPaint()

            End If

        Catch ex As Exception
            HandleException("frmCampaignRunner.NextPlayer", ex)
        End Try

    End Sub

    Private Sub SetParams()
        Try
            '// mark the property with the computername and the authkey
            '// run when saved

            '// see if the property exists for this player
            '            If CurrentGame.ExtendedProperties Is Nothing Then CurrentGame.ExtendedProperties = New GenericProperties

            '            For Each jeep As GenericProperty In CurrentGame.ExtendedProperties
            '                If jeep.PropertyName = CurrentGame.selectedPlayer.PlayerName Then
            '                    '// do the stuff and exit
            '                    jeep.PropertyValue = _param & ":" & My.Computer.Name

            '#If DEBUG Then
            '                    Debug.WriteLine(jeep.PropertyValue)
            '#End If

            '                    Exit Sub
            '                End If
            '                Debug.WriteLine("Name: " & jeep.PropertyName & "   || Value: " & jeep.PropertyValue)
            '            Next

            '            '// if we made it here, the gp doesn't exist
            '            updateParams()


            If CurrentGame.ExtendedProperties Is Nothing Then CurrentGame.ExtendedProperties = New GenericProperties

            '// clear old properties
            CurrentGame.ExtendedProperties.Clear()

            '// insert this computer/authkey
            Dim jeep As New GenericProperty()
            jeep.PropertyName = _param
            jeep.PropertyValue = My.Computer.Name

            CurrentGame.ExtendedProperties.Add(jeep)

#If DEBUG Then
            Debug.WriteLine(jeep.PropertyValue)
#End If

        Catch ex As Exception
            HandleException("frmCampaignRunner.SetParams", ex)
        End Try
    End Sub

    Private Function checkParams() As Boolean
        Try
            '// returns true if acceptable

            '// for now, we'll just go ahead and say its good.
            Return True

            '// runs when loaded.
            If CurrentGame.ExtendedProperties Is Nothing Then CurrentGame.ExtendedProperties = New GenericProperties

            If CurrentGame.ExtendedProperties.Count = 0 Then Return True '// no reason to be in here until the game is saved and properties set.

            '// begin the checking!
            Dim jeep As GenericProperty = CurrentGame.ExtendedProperties.item(0)

            If jeep.PropertyName = _param Then
                If jeep.PropertyValue <> My.Computer.Name Then '// different computer, same authkey
                    '// houston, we have a problem.
                    Return False
                End If
            Else
                Return True
            End If

        Catch ex As Exception
            HandleException("frmCampaignRunner.checkParams", ex)
            Return False
        End Try
    End Function

    Private Sub updateParams()
        Try

            Dim gp As New GenericProperty
            gp.PropertyName = CurrentGame.selectedPlayer.PlayerName
            gp.PropertyValue = _param & ":" & My.Computer.Name
            CurrentGame.ExtendedProperties.Add(gp)

        Catch ex As Exception
            HandleException("frmCampaignRunner.updateParams", ex)
        End Try
    End Sub

    Private Sub ShowCombatResolution()
        Try
            resCombatResolution.Visible = True
            resCombatResolution.Size = New Size(chiSelected.Size)
            resCombatResolution.Anchor = chiSelected.Anchor
            resCombatResolution.Location = chiSelected.Location
            resCombatResolution.ListBattles(CurrentGame, fmpMap.FlexMap)

            If Not Me.Controls.Contains(resCombatResolution) Then
                Me.Controls.Add(resCombatResolution)
                resCombatResolution.BringToFront()
            End If

            '// tell the map that it's time to show all the battles
            fmpMap.RedrawMapForCombatResolution()
        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try
    End Sub

    Private Function AllPlayersCompleted() As Boolean
        Try
            Dim key As String
            Dim play As Player

            For Each key In CurrentGame.Players.Keys
                play = CType(CurrentGame.Players.Item(key), Player)
                If Not play.PlayerName = "<Moderator>" Then
                    '// if at least one player is not completed, then we wait.
                    '// we ignore no play for checking
                    If play.NoPlay = False Then If play.TurnComplete = False Then Return False
                End If
            Next
            '// if nothing has returned false already, we must be okay.
            Return True
        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try

    End Function

    Private Sub ResetPlayerComplete()
        Dim key As String
        Dim play As Player

        For Each key In CurrentGame.Players.Keys
            play = CType(CurrentGame.Players.Item(key), Player)
            If play.PlayerName <> "Moderator" Then
                play.TurnComplete = False
            End If
        Next
    End Sub

    Private Function ResetForCombatPlayers() As Integer
        Dim playKey As String
        Dim play As Player
        Dim numNotInCombat As Integer

        Try
            For Each playKey In CurrentGame.Players.Keys
                play = CurrentGame.Players.Item(playKey)
                If play.PlayerName <> "<Moderator>" Then
                    If play.IsInCombat Then
                        ' only show players currently in combat.
                        play.TurnComplete = False
                    Else
                        play.TurnComplete = True
                        numNotInCombat += 1
                    End If
                End If
            Next
            ' return the number of players not in combat 
            Return numNotInCombat
        Catch ex As Exception
            HandleException("frmCampaignRunner.ResetForCombatPlayers", ex)
        End Try

    End Function

    Private Property DeployUnit() As Boolean
        Get
            Return _DeployUnit
        End Get
        Set(ByVal Value As Boolean)
            _DeployUnit = Value
            fmpMap.Deployment = Value
            tlbToolbar.deployButton.checked = Value
        End Set
    End Property


    Delegate Sub OTM()

    Private Sub OffThreadMessagebox()

        Dim fart As New OTM(AddressOf InitiateMessagebox)
        fart.BeginInvoke(Nothing, Nothing)

    End Sub

    Private Sub InitiateMessagebox()
        MessageBox.Show("Generating New Turn...", "Info: New Turn", MessageBoxButtons.OK, MessageBoxIcon.Information)
    End Sub

    Private Sub GenerateTurn()
        Try
            InitiateMessagebox()    '// no longer off-thread, didn't fix anything. :(

            If CurrentGame.Turn = 0 Then
                CurrentGame.ResetRemainingTime()
                CurrentGame.Turn = 1
            End If

            '// alrighty, check for game completion
            If CurrentGame.Turn = CurrentGame.MaxTurns Then
                '// game is OVER and we don't do any more uhm... generating.
                If CurrentGame.gameEndDetails Is Nothing Then CurrentGame.gameEndDetails = New EndGame
                CurrentGame.gameEndDetails.GameEnded = True
                CurrentGame.gameEndDetails.turnRunOut = True
                Exit Sub
            End If

            '// check for duplicate keys because its such a huge problem... :P
            If DupKey() = True Then
                MessageBox.Show("Duplicate key detected, turn will not be generated.", "Duplicate Key", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                Exit Sub
            End If

            newTurnGrinder = New CampaignerCombatEngineB 'CampaignerCombatEngine.ConquestCombatEngine 'CampaignerCombatEngine.CampaignerCombatEngineB
            AddHandler newTurnGrinder.PercentComplete, AddressOf newTurnGrinder_PercentComplete

            newTurnGrinder.FlexMap = fmpMap.FlexMap
            newTurnGrinder.pixelsPerOneMile = fmpMap.PixelsPerOneMile

            newTurnGrinder.GenerateCombatTurn(CurrentGame) ', c_COMBATPHASES)

            Dim pixelsPerOneMile As Integer = fmpMap.FlexMap.MapScale.PixelCount / fmpMap.FlexMap.MapScale.MilesPerPixelCount

            ' Reset moveremaining and status and battle involved in for next turn, only if remainingTime is zero.
            If CurrentGame.remainingTime <= TimeSpan.Zero Then
                For Each mem As ChitMember In CurrentGame.Chits
                    If mem.UnitType = GroundChitClass_cgd.Battlegroup Then
                        ' determine how many pixels a unit can move per game turn.
                        DirectCast(mem, BattlegroupChit).moveRemaining = DirectCast(mem, BattlegroupChit).movementSpeed * pixelsPerOneMile
                        'unit.MoveRemaining = unit.MovementSpeed * pixelsPerOneMile
                    Else
                        '// the generate resources will also handle "Deployment Points" when the owning installation is at max capacity, 
                        '// it will add those points to the owning faction's available points
                        DirectCast(mem, InstallationChit).GenerateResources()
                    End If

                    '// since anything can have rules...
                    mem.ResetRuleCount()

                    '// consume constant resources
                    '// bwaaaaaaaaaaa :(

                    '// lets calculate the total deployed point value.
                    CalculateCurrentDeployedPV()
                    FulfillVictoryConditions()
                    CheckForFinalVictory()

                    '// here we check for the capturing and destroying of DEPLOYMENT ZONES
                    checkDeploymentZoneCaptures(CurrentGame)

                    '// here, we reset the deployment zone amounts, instead of elsewhere
                    newTurnGrinder.ResetDeploymentValues(CurrentGame)

                Next
                '// reset the time remaining for the next turn.
                CurrentGame.ResetRemainingTime()
                newTurnGrinder.ResetStatus() '// reset status of units
                CurrentGame.Turn += 1 '// this may no longer be needed...
            End If

            CurrentGame.AverageUnitMaxPV = CalculateAverageMaxPV(GroundChitClass_cgd.Unit)
            CurrentGame.AverageObjectiveMaxPV = CalculateAverageMaxPV(GroundChitClass_cgd.Objective)

            '// update stats stuff.
            chiSelected.PopulateStatisticBenchmarks()

        Catch ex As Exception
            HandleException("frmCampaignRunner.GenerateTurn", ex)
        End Try

    End Sub

    Private Function EString(ByVal value As String) As String
        '// encrypt string
        Try

        Catch ex As Exception

        End Try
    End Function

    Private Function DupKey() As Boolean
        Try

            'Dim ht As New Hashtable
            'For Each jeep As GenericProperty In CurrentGame.ExtendedProperties
            '    Try
            '        If Not ht.ContainsKey(jeep.PropertyValue) Then
            '            ht.Add(jeep.PropertyValue, jeep)
            '        End If
            '    Catch ex As Exception
            '        '// duplicate key::computername ignored (playing locally)
            '        '// this means this player has hit "next player" at the same computer as another player. 
            '    End Try
            'Next

            ''// any players left in the HT should have DIFFERENT keys (first 22)
            'Try
            '    Dim HHT As New Hashtable
            '    For Each KEY As String In ht.Keys
            '        Dim jeep As GenericProperty = ht.Item(KEY)
            '        Dim s As String = jeep.PropertyValue.Substring(0, 22)
            '        '// only add it if it isn't the demo value
            '        If Not s.ToLower.Equals("xxxxxx-xxxx-xxxx-xxxxxx") Then HHT.Add(s, s)
            '    Next
            '    '// success. They are not using duplicate keys. Amazing.
            '    Return False
            'Catch ex As Exception
            '    '// bad bad bad. Thief!!! >:O, unless they are both xxxxx-xxxx-... etc
            '    Return True
            'End Try

            Return False '// not using duplicate keys

        Catch ex As Exception
            HandleException(c_Module & ".DupKey", ex)
            Return True '// must be using a duplicate key? dunno
        End Try
    End Function


    Private Function CalculateAverageMaxPV(ByVal GCClass As GroundChitClass_cgd) As Int32
        Dim gcCount As Int16
        Dim totalPV As Int32
        Dim calculatedAverage As Int32

        Try
            For Each mem As ChitMember In CurrentGame.Chits
                If mem.UnitType = GroundChitClass_cgd.Battlegroup Then
                    gcCount += 1
                    totalPV += DirectCast(mem, BattlegroupChit).deployedpointvalue
                End If

            Next

            If gcCount <> 0 Then
                If totalPV <> 0 Then
                    calculatedAverage = totalPV / gcCount
                End If
            End If
        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try

        Return calculatedAverage
    End Function

    Private Function CalculateMaxDeployedPV(ByVal GCClass As GroundChitClass_cgd) As Int32
        CurrentGame.calculateMaxDeployedPV()
        Return CurrentGame.MaxPointValueDeployed

    End Function

    Private Sub CalculateCurrentDeployedPV()
        Dim fact As Faction
        Dim factKey As String
        Dim dep As Long

        Try
            For Each factKey In CurrentGame.Faction_g.HT.Keys
                fact = CurrentGame.Faction_g.Item(factKey)

                For Each mem As ChitMember In CurrentGame.Chits

                    If mem.OwningFaction.Equals(fact) Then
                        If mem.UnitType = GroundChitClass_cgd.Battlegroup Then
                            If Not mem.Status = GroundUnitStatus_cgd.Dead Then dep += DirectCast(mem, BattlegroupChit).CurrentPV
                        End If
                    End If
                Next

                fact.FactionDeployedPoints = dep
                dep = 0
            Next

        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try

    End Sub


#Region "Victory Conditions"

    Private Sub FulfillVictoryConditions()
        Dim fact As Faction
        Dim factkey As String
        Dim vict As IVictoryCondition

        Try
            For Each factkey In CurrentGame.Faction_g.HT.Keys
                fact = CurrentGame.Faction_g.Item(factkey)
                For Each vict In fact.FactionVictoryConditions
                    Select Case vict.VCType
                        Case VictoryConditionClass_cgd.AreaObjective
                            If IsAOVictoryMet(vict, fact) Then
                                vict.Achieved = True

                            Else
                                vict.Achieved = False
                            End If
                        Case VictoryConditionClass_cgd.AttritionObjective
                            If IsAttritionVictoryMet(vict, fact) Then
                                vict.Achieved = True
                            Else
                                vict.Achieved = False
                            End If
                        Case VictoryConditionClass_cgd.ChitDestruction
                            If IsChitDestructionVictoryMet(vict) Then
                                vict.Achieved = True
                            Else
                                vict.Achieved = False
                            End If
                        Case VictoryConditionClass_cgd.Resource
                            If IsResourceVictoryMet(vict, fact) Then
                                vict.Achieved = True
                            Else
                                vict.Achieved = False
                            End If
                        Case Else
                            ' this would be finalvictory. We calculate that later.

                    End Select
                Next
            Next
        Catch ex As Exception
            HandleException("frmCampaignRunner.FulfillVictoryConditions", ex)
        End Try

    End Sub

    Private Function IsAOVictoryMet(ByRef AOVict As AreaObjectiveVictoryCondition, ByRef forFact As Faction) As Boolean
        Try
            If AOVict.TargetAreaObjective.OwningFaction = forFact.FactionID Then
                If Not AOVict.TargetAreaObjective.IsContested Then
                    Return True
                Else
                    Return False
                End If

            Else
                Return False
            End If
        Catch ex As Exception
            HandleException("frmCampaignRunner.IsAOVictoryMet", ex)
        End Try

    End Function

    Private Function IsAttritionVictoryMet(ByRef ATVict As AttritionVictoryCondition, ByVal forFact As Faction) As Boolean
        Dim factKey As String
        Dim otherFact As Faction

        Try
            For Each factKey In CurrentGame.Faction_g.HT.Keys
                otherFact = CurrentGame.Faction_g.Item(factKey)
                If otherFact.FactionID <> forFact.FactionID Then
                    Exit For
                End If
            Next

            Dim depPoints As Long
            Dim totalDep As Long
            Dim maxPoints As Long
            Dim freePoints As Long  '// points not deployed
            Dim NumberRequirements As Byte
            Dim numberRequirementsMet As Byte

            depPoints = otherFact.FactionDeployedPoints
            totalDep = otherFact.FactionTotalDeployedPoints
            maxPoints = otherFact.FactionTotalPoints
            freePoints = otherFact.FactionFreePoints

            If ATVict.DeployedReductionPercent <> -1 Then
                NumberRequirements += 1
                Try
                    Dim per As Single = (depPoints / totalDep) * 100
                    If per <= ATVict.DeployedReductionPercent Then
                        numberRequirementsMet += 1
                    End If
                Catch ex As Exception
                    HandleException(c_Module, ex)
                End Try
            End If

            If ATVict.TotalPointValueReductionPercent <> -1 Then
                NumberRequirements += 1
                Try
                    Dim per As Single = (depPoints / (maxPoints - freePoints)) * 100
                    If per <= ATVict.TotalPointValueReductionPercent Then
                        numberRequirementsMet += 1
                    End If
                Catch ex As Exception
                    HandleException(c_Module, ex)
                End Try
            End If

            If numberRequirementsMet = NumberRequirements Then
                Return True
            Else
                Return False
            End If

        Catch ex As Exception
            HandleException("frmCampaignRunner.IsAttritionVictoryMet", ex)
        End Try

    End Function

    Private Function IsChitDestructionVictoryMet(ByRef CDVictory As ChitDestructionVictoryCondition) As Boolean
        Try
            If CDVictory.ChitToDestroy.Status = GroundUnitStatus_cgd.Dead Then Return True
        Catch nullEx As NullReferenceException
            Return True ' its gone man!
        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try

        ' if its not dead and it exists, the victory condition is NOT met.
        Return False

    End Function

    Private Function IsResourceVictoryMet(ByRef RSVict As ResourceVictoryCondition, ByRef forFact As Faction) As Boolean
        Dim currentResAmount As Long
        Try
            Dim cm As ChitMember
            Dim inst As InstallationChit

            For Each cm In CurrentGame.Chits
                If cm.OwningFaction.FactionID = forFact.FactionID Then
                    If TypeOf cm Is InstallationChit Then
                        inst = cm
                        For Each resitem As ResourcePoolItem In inst.Resources
                            If resitem.resourceTypeptr.Equals(RSVict.TargetResourceType) Then
                                currentResAmount += resitem.localAmount
                                If currentResAmount >= RSVict.AmountNeeded Then
                                    Return True
                                End If
                            End If
                        Next
                    End If
                End If
            Next

        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try

        ' if we don't short-circuit, we don't have enough.
        Return False

    End Function

    Private Sub CheckForEndGame()
        Try
            '// if the Ignore button was pressed, there will be no further checks for end game.
            If CurrentGame.gameEndDetails.Ignore Then Exit Sub '// if all players ignore, this flag should be set.

            If CurrentGame.gameEndDetails.GameEnded = False Then
                CheckForTurnRunOut()
                CheckForFinalVictory()
            End If

            If CurrentGame.gameEndDetails.GameEnded = True Then
                '// now we can say, HEY! Quit playing! It's OVER!
                '// if the player does not have ignore end game set, we'll pop up the end game form.
                '// demo can't IGNORE. When its over, its over.
                If Not CurrentGame.selectedPlayer Is Nothing Then
                    If CurrentGame.selectedPlayer.IgnoreEndGame = False Then
                        Dim f As New camp128c.frmEndGame
                        f.showDialog(CurrentGame)
                    End If
                End If

            End If

        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try
    End Sub

    Private Sub CheckForTurnRunOut()
        Try
            If CurrentGame.Turn >= CurrentGame.MaxTurns Then
                CurrentGame.gameEndDetails.GameEnded = True
                CurrentGame.gameEndDetails.turnRunOut = True
            End If
        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try
    End Sub

    Private Sub CheckForFinalVictory()
        'TASK: final victory
        ' all we currently do is post a messagebox saying... "hey, joe won"
        ' later, a window will show or something. I dunno.
        Dim fact As Faction
        Dim victRes As String 'YY or NN or YN or NY
        Dim factKey As String
        Dim totalAchievedVP As Integer
        Dim requiredVP As Integer
        Dim vict As IVictoryCondition

        Try
            For Each factKey In CurrentGame.Faction_g.HT.Keys
                fact = CurrentGame.Faction_g.Item(factKey)
                totalAchievedVP = 0
                Dim factFinal As FinalVictoryCondition
                Dim autoVictory As Boolean = False

                '// check for no victory conditions
                If Not fact.FactionVictoryConditions Is Nothing Then
                    If fact.FactionVictoryConditions.Count > 0 Then
                        For Each vict In fact.FactionVictoryConditions
                            If vict.Achieved = True Then
                                totalAchievedVP += vict.VPValue
                                If vict.AutomaticVictory = True Then
                                    autoVictory = True
                                End If
                            End If

                            If TypeOf vict Is FinalVictoryCondition Then
                                factFinal = vict
                            End If
                        Next

                        If factFinal.VPValue > 0 Then
                            If totalAchievedVP >= factFinal.VPValue Then
                                CurrentGame.gameEndDetails.GameEnded = True
                                CurrentGame.gameEndDetails.VictoryWin = True
                            ElseIf autoVictory = True Then
                                CurrentGame.gameEndDetails.GameEnded = True
                                CurrentGame.gameEndDetails.VictoryWin = True
                            End If
                        End If
                    End If
                End If

            Next

        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try
    End Sub
#End Region

    Private Sub Moderator()
        Dim frmMod As New frmModeratorActions(CurrentGame)
        frmMod.ShowDialog()
    End Sub


    Private Function CheckForUnresolvedCombats(ByRef allPlayersComplete As Boolean) As Boolean
        ' returns if there are unresolved combats
        ' the all players complete parameter determines if the End of combat screen should be shown.
        Dim batt As Battle
        Dim battKey As String
        Dim bUnresolvedRemaining As Boolean = False

        Try
            For Each battKey In CurrentGame.Battles_g.HT.Keys
                batt = CurrentGame.Battles_g.Item(battKey)
                If batt.BattleResult = BattleResult_cgd.NotFinished Then
                    bUnresolvedRemaining = True
                    Exit For
                End If
            Next

            ' default to all players complete
            allPlayersComplete = True

            If bUnresolvedRemaining = True Then
                Dim play As Player
                Dim playKey As String
                For Each playKey In CurrentGame.Players.Keys
                    play = CurrentGame.Players.Item(playKey)
                    If Not play.PlayerName = "<Moderator>" Then
                        If play.TurnComplete = False Then
                            allPlayersComplete = False

                            Exit For
                        End If
                    End If
                Next
            End If
        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try

        Return bUnresolvedRemaining

    End Function

    Private Sub p()

        _authenticated = True
        Exit Sub

        'Dim cc As New Cryptkeeper
        'Dim opString As String = cc.DString("htd~fo dffo rhnn qi{wgq") '"grazan aban odim nevven"
        'Dim firstopen As Boolean = False

        'Try

        '    Dim local As RegistryKey = My.Computer.Registry.LocalMachine
        '    Dim software As RegistryKey = local.OpenSubKey(cc.DString("TQIX\BTH"), True) 'SOFTWARE
        '    Dim racing As RegistryKey = software.OpenSubKey(cc.DString("Scfmshusmift Kfngv"), True) 'Racingspider Games
        '    Dim campaignerAuth As RegistryKey


        '    If racing Is Nothing Then
        '        '// create it all
        '        racing = software.CreateSubKey(cc.DString("Scfmshusmift Kfngv")) 'Racingspider Games
        '        campaignerAuth = racing.CreateSubKey(cc.DString("dcptfjiqiw"), RegistryKeyPermissionCheck.ReadWriteSubTree) ' campaigner
        '        campaignerAuth.SetValue(cc.DString("dcptfjiqiw"), cc.DString("htd~fo dffo rhnn qi{wgq")) 'campaigner   grazan aban odim nevven
        '        firstopen = True
        '    Else
        '        campaignerAuth = racing.OpenSubKey(cc.DString("dcptfjiqiw"), True) 'campaigner
        '        If campaignerAuth Is Nothing Then
        '            '// the campaigner level is not part of the registry (maybe they just have VT)
        '            campaignerAuth = racing.CreateSubKey(cc.DString("dcptfjiqiw")) 'campaigner
        '            campaignerAuth.SetValue(cc.DString("dcptfjiqiw"), cc.DString("yz{|}y-{|}y-{|}y-{|}yz{")) 'campaigner   xxxxxx-xxxx-xxxx-xxxxxx
        '        End If
        '    End If

        '    opString = campaignerAuth.GetValue(cc.DString("dcptfjiqiw")) 'campaigner



        '    If VerifyDebugOutput(opString) = 200 Then
        '        '// we're okay to continue. Yay.
        '        _authenticated = True
        '        _param = opString
        '        Exit Sub
        '    Else
        '        firstopen = True
        '    End If

        '    Dim fa As New frmAuthenticateForm
        '    fa.ShowDialog()
        '    opString = fa.key

        '    If VerifyDebugOutput(opString) = 200 Then
        '        'c1 =campaigner
        '        Dim c1 As String = "dcptfjiqiw"

        '        _authenticated = True
        '        campaignerAuth.SetValue(cc.DString(c1), opString)

        '        _param = opString

        '        If firstopen = True Then
        '            Dim s1 As String = "Ujdrp {ry gqu fvvkisukfeyjpj Hbosenhphv. [ry oqz mbxh kvno ztg sk vki t{vxjn."
        '            Dim s2 As String = "Bwwljovlgfugg [ftvmto"
        '            'MessageBox.Show("Thank you for authenticating Campaigner. You now have full use of the system.", "Authenticated Version", MessageBoxButtons.OK)
        '            MessageBox.Show(cc.DString(s1), cc.DString(s2), MessageBoxButtons.OK)
        '        End If
        '    Else
        '        _authenticated = False
        '        Dim s As String = "Zqx fsg tqb{lrl kq ifor rpfh fof gfo rrqz rtjo girp ferqclkst."
        '        Dim s2 As String = "Egps Nqgi"
        '        'MessageBox.Show("You are playing in demo mode and can only open demo campaigns.", "Demo Mode", MessageBoxButtons.OK)
        '        MessageBox.Show(cc.DString(s), cc.DString(s2))
        '    End If

        'Catch ex As Exception
        '    MessageBox.Show(ex.Message & " error received", "Error Received", MessageBoxButtons.OK, MessageBoxIcon.Error)
        '    _authenticated = False
        'End Try
    End Sub

    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        p()
        ' Add any initialization after the InitializeComponent() call.
        '// initialize our combat assets control
        Try
            comCombats.Visible = False
            comCombats.Anchor = Me.chiSelected.Anchor
            comCombats.Location = chiSelected.Location
            comCombats.Size = chiSelected.Size
            Me.Controls.Add(comCombats)
            resCombatResolution.Visible = False

            lblPointsAvailable.Visible = False

        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try
    End Sub

    Private Sub fmpMap_BattlegroupButtonPressed(ByRef member As cmplib01.ChitMember) Handles fmpMap.BattlegroupButtonPressed
        Try

            If member.UnitType = GroundChitClass_cgd.Battlegroup Then
                Dim f As New frmBattlegroupManager()
                f.showdialog(CurrentGame, member, fmpMap.FlexMap)
                fmpMap.RedrawAndRender()

            End If

        Catch ex As Exception

        End Try
    End Sub

    Private Sub fmpMap_chitSelected(ByRef member As cmplib01.ChitMember) Handles fmpMap.chitSelected
        Try
            If mTurnMode = TurnMode.CombatTurn Then
                '// in combat mode, nothing stays selected so there can be no waypoint set. ha.
                fmpMap.ClearSelectedChit()
                '// if its friendly:
                Dim friendly As Boolean = False
                If member.OwningFaction.Equals(CurrentGame.selectedFaction) Then
                    friendly = True
                End If

                Dim f As New frmChitProperties(member, member.detectionLevelThisTurn, CurrentGame, friendly)
                f.ShowDialog()



            Else
                chiSelected.PixelsPerOneMile = fmpMap.FlexMap.PixelsPerOneMile
                chiSelected.ShowSelectedChitProperties(member, CurrentGame)
            End If

        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try
    End Sub

    Private Sub fmpMap_chitUnselected() Handles fmpMap.chitUnselected
        Try
            chiSelected.ClearSelectedList()
        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try
    End Sub

    Private Sub fmpMap_DeployRequest(ByVal location As System.Drawing.Point) Handles fmpMap.DeployRequest
        Dim DeployMan As New camp128c.cDeploymentManager

        Try
            If DeployMan.AttemptDeploy(CurrentGame, fmpMap.FlexMap, New Point(location.X, location.Y)) = True Then
                fmpMap.RedrawAndRender()
                ' set up the new event for this action
                Dim Levent As New CampaignerLogEvent
                Levent.logMessage = "unit deployed"
                Levent.logSource = CurrentGame.selectedPlayer.PlayerName
                Levent.AuthorityLevel = EventAuthorityLevel.OwningEvent
                Levent.ExtendedProperties = "<none>"
                Levent.timeStamp = CurrentGame.ElapsedTime.ToString

                ' add the event
                CurrentGame.LogEvents.Add(Levent)
                updatePointsAvailableText()
            End If
        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try
    End Sub

    Private Sub fmpMap_enemySelected(ByRef member As cmplib01.ChitMember) Handles fmpMap.enemySelected
        Try
            Dim f As New frmChitProperties(member, member.detectionLevelThisTurn, CurrentGame, False)
            f.ShowDialog()

        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try

    End Sub

    Private Sub fmpMap_waypointChange() Handles fmpMap.waypointChange
        chiSelected.ShowSelectedChitProperties(fmpMap.SelectedChit, Me.CurrentGame)
        fmpMap.RedrawAndRender()
    End Sub

    Private Sub newTurnGrinder_PercentComplete(ByVal percent As Integer) Handles newTurnGrinder.PercentComplete
        GameTitle = "Campaigner: Processing Turn [" & percent & "%]"
        If percent = 100 Then
            GameTitle = "Campaigner: Processing Turn Completed"
        End If
        Invalidate()
    End Sub

    Private Sub ApplyCombatResults() Handles resCombatResolution.AllBattlesFinished
        newTurnGrinder.ApplyCombatResults(CurrentGame)
        resCombatResolution.Visible = False
        ResetPlayerComplete()
        mTurnMode = TurnMode.NormalTurn

        '// clear all battles
        ClearAllBattles()

    End Sub

    Private Sub ClearAllBattles()
        Try
            '// in the future, we'll make an historical record of the battles
            CurrentGame.Battles_g.HT.Clear()
        Catch ex As Exception
            HandleException(c_Module, ex)
        End Try
    End Sub

    Private Sub tlbToolbar_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tlbToolbar.Load

    End Sub

    Private Sub chiSelected_ShowRuleRange(ByVal ruleio As cmplib01.Rule) Handles chiSelected.ShowRuleRange
        fmpMap.DrawRuleRange(ruleio.ptrRule.BasicRange * fmpMap.PixelsPerOneMile, New Point(chiSelected.SelectedChit.PreciseLocation.X, chiSelected.SelectedChit.PreciseLocation.Y))

    End Sub

    Private Sub frmCampaigner_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
        If Me.WindowState = FormWindowState.Minimized Then
            Me.Text = "Campaigner"
        Else
            Me.Text = ""
        End If
    End Sub

    Private Sub picMaximize_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles picMaximize.Click
        If WindowState = FormWindowState.Maximized Then
            WindowState = FormWindowState.Normal
            picMaximize.Image = My.Resources.maximize
        Else
            WindowState = FormWindowState.Maximized
            picMaximize.Image = My.Resources.restore
        End If
    End Sub

    Private Sub picMinimize_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles picMinimize.Click
        WindowState = FormWindowState.Minimized
    End Sub

    Private Class Cryptkeeper
        Private Const seed As Integer = 243

        Public Function EncodeString(ByVal s As String) As String

            Dim index As Integer
            Dim c(s.Length - 1) As Char
            Dim randy As New Random(seed)

            Dim counter As Integer

            For index = 0 To s.Length - 1
                counter += 1
                If counter = 6 Then counter = 1

                If Asc(s.Substring(index, 1)) >= 65 AndAlso Asc(s.Substring(index, 1)) <= 122 Then
                    c(index) = Chr(Asc(s.Substring(index, 1)) + counter)

                Else
                    '// don't do anything special
                    c(index) = s.Substring(index, 1)
                End If

            Next

            Return c

        End Function

        Public Function DString(ByVal s As String) As String
            Dim c(s.Length - 1) As Char
            Dim j(s.Length - 1) As Char
            Dim index As Integer
            Dim randy As New Random(seed)

            Dim counter As Integer

            '// reverse step 2
            For index = 0 To c.Length - 1
                counter += 1
                If counter = 6 Then counter = 1
                If Asc(s.Substring(index, 1)) >= 64 AndAlso Asc(s.Substring(index, 1)) <= 127 Then
                    Dim bones As Int16 = Asc(s(index))
                    c(index) = Chr(bones - counter)
                Else
                    c(index) = s.Substring(index, 1)
                End If
            Next

            Return c
        End Function

    End Class

    Private Class Messages

    End Class



End Class